package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : Bing
 * @Date 2023/3/2 18:52
 */
@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class AutoCreateSupplyTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {

        //解析消息
        SupplyContract contract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);


        VmVO vmInfo = vmService.getVMInfo(contract.getInnerCode());

        Integer leastUser = taskService.getLeastUser(vmInfo.getRegionId(), Boolean.FALSE);

        if (!CollectionUtils.isEmpty(contract.getSupplyData())) {

            //遍历补货信息
            List<TaskDetailsViewModel> collect = contract.getSupplyData().stream().map(each -> {
                TaskDetailsViewModel model = new TaskDetailsViewModel();
                model.setChannelCode(each.getChannelId());
                model.setExpectCapacity(each.getCapacity());
                BeanUtils.copyProperties(each, model);
                return model;
            }).collect(Collectors.toList());

            //创建补货工单
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0);
            taskViewModel.setInnerCode(contract.getInnerCode());
            taskViewModel.setUserId(leastUser);
            taskViewModel.setAssignorId(0);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setDetails(collect);

            try {
                taskService.createTask(taskViewModel);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

}
